package com.example.puzzle;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.GridLayout;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView[][] iv_game_arr = new ImageView[4][4];
    private GridLayout gl_main_game;
    private ImageView iv_null_Image;
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //原始大图片
        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.xcm1)).getBitmap();
        int tuWandHeight = bitmap.getWidth() / 5;
        gl_main_game = findViewById(R.id.gl_main_game);
        for (int i = 0; i < iv_game_arr.length; i++) {
            for (int j = 0; j < iv_game_arr[0].length; j++) {
                Bitmap bitmap1 = Bitmap.createBitmap(bitmap, j * tuWandHeight, i * tuWandHeight, tuWandHeight, tuWandHeight);
                iv_game_arr[i][j] = new ImageView(this);
                iv_game_arr[i][j].setImageBitmap(bitmap1);
                iv_game_arr[i][j].setPadding(2, 2, 2, 2);
                iv_game_arr[i][j].setTag(new GameData(i, j, bitmap1));
                iv_game_arr[i][j].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //监听判断照片位置的状态
                        boolean flag = isHasByNullImageView((ImageView) v);
                        Log.e("MainActivity", "onClick: 和空方块的关系相邻为true否则为false----" + flag);
                        if (flag) {
                            changeDataByImageView((ImageView) v);
                            Log.e("MainActivity", "onClick: 方块位置交换成功----" + flag);
                        }
                    }
                });


            }
        }
        for (int i = 0; i < iv_game_arr.length; i++) {
            for (int j = 0; j < iv_game_arr[0].length; j++) {
                gl_main_game.addView(iv_game_arr[i][j]);
            }
        }
        setNullImageView(iv_game_arr[3][3]);
        //绑定手势
        gestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {

            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                int sType = getDirByGes(e1.getX(), e1.getY(), e2.getX(), e2.getY());
                Log.e("GestureDetector", "onFling: 手势的方向（1）上（2）下（3）左（4）右------" + sType);
                changeByDir(sType);
                return false;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    //设置某个方块为空的
    public void setNullImageView(ImageView imageView) {
        imageView.setImageBitmap(null);
        iv_null_Image = imageView;
    }

    //判断当前点击的方块是否与空方块的位置是相邻的
    public boolean isHasByNullImageView(ImageView imageView) {
        GameData mNullIGameData = (GameData) iv_null_Image.getTag();//空方块的位置
        GameData mGameData = (GameData) imageView.getTag();//非空方块的位置
        //判断方块的位置
        if (mNullIGameData.y == mGameData.y && mNullIGameData.x == mGameData.x + 1) {
            return true;
        } else if (mNullIGameData.y == mGameData.y && mNullIGameData.x == mGameData.x - 1) {
            return true;
        } else if (mNullIGameData.y == mGameData.y + 1 && mNullIGameData.x == mGameData.x) {
            return true;
        } else if (mNullIGameData.y == mGameData.y - 1 && mNullIGameData.x == mGameData.x) {
            return true;
        }
        return false;
    }

    //交换方块的数据
    public void changeDataByImageView(final ImageView imageView) {
        //创建一个动画，设置好方向和移动的距离
        TranslateAnimation translateAnimation = null;
        if (imageView.getX() > iv_null_Image.getX()) {
            translateAnimation = new TranslateAnimation(0.1f, -imageView.getWidth(), 0.1f, 0.1f);
        } else if (imageView.getX() < iv_null_Image.getX()) {
            translateAnimation = new TranslateAnimation(0.1f, imageView.getWidth(), 0.1f, 0.1f);
        } else if (imageView.getY() > iv_null_Image.getY()) {
            translateAnimation = new TranslateAnimation(0.1f, 0.1f, 0.1f, -imageView.getWidth());
        } else if (imageView.getY() < iv_null_Image.getY()) {
            translateAnimation = new TranslateAnimation(0.1f, 0.1f, 0.1f, imageView.getWidth());
        }
        //设置动画的时长
        translateAnimation.setDuration(60);
        //设置动画结束后的状态
        translateAnimation.setFillAfter(true);
        //设置在动画结束后把所以小方块的数据都交换
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageView.clearAnimation();
                GameData gameData = (GameData) imageView.getTag();
                iv_null_Image.setImageBitmap(gameData.sBitmap);
                GameData nullGameData = (GameData) iv_null_Image.getTag();
                nullGameData.p_x = gameData.p_x;
                nullGameData.p_y = gameData.p_y;
                nullGameData.sBitmap = gameData.sBitmap;
                setNullImageView(imageView);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        imageView.startAnimation(translateAnimation);
    }

    //每个方块的数据
    class GameData {
        //每个小方块的实际位置 x 坐标
        public int x = 0;
        //每个小方块的实际位置 y 坐标
        public int y = 0;
        //每个小方块的图片
        public Bitmap sBitmap;
        //每个小方块的图片的位置
        public int p_x = 0;
        public int p_y = 0;

        public GameData(int x, int y, Bitmap sBitmap) {
            super();
            this.x = x;
            this.y = y;
            this.sBitmap = sBitmap;
            this.p_x = x;
            this.p_y = y;

        }
    }

    //手势滑动类
    public int getDirByGes(float start_x, float start_y, float end_x, float end_y) {
        boolean isLeftOrRight = (Math.abs(start_x - end_x) > Math.abs(start_y - end_y)) ? true : false;
        if (isLeftOrRight) {
            boolean isLeft = start_x - end_x > 0 ? true : false;
            if (isLeft) {
                return 3;//左
            } else {
                return 4;//右
            }
        } else {
            boolean isUp = start_y - end_y > 0 ? true : false;
            if (isUp) {
                return 1;//上
            } else {
                return 2;//下
            }
        }
    }

    public void changeByDir(int type) {
        GameData mNullGameData = (GameData) iv_null_Image.getTag();
        int new_x = mNullGameData.x;
        int new_y = mNullGameData.y;
        if (type == 1) {
            new_x++;
        } else if (type == 2) {
            new_x--;
        } else if (type == 3) {
            new_y++;
        } else if (type == 4) {
            new_y--;
        }
        if (new_x>=0&&new_x<iv_game_arr.length&&new_y>=0&&new_y<iv_game_arr[0].length){
            changeDataByImageView(iv_game_arr[new_x][new_y]);
        }
    }
}
